# -*- coding: utf-8 -*-
# @Time    : 2024/11/10 14:07
# @Author  : CHNJX
# @File    : middleware.py
# @Desc    :


from functools import wraps
from flask import request, g, current_app
import time
from ..utils.response_handler import error_response


def request_logger(f):
    """请求日志中间件"""

    @wraps(f)
    def decorated(*args, **kwargs):
        # 记录请求开始时间
        start_time = time.time()

        # 获取请求信息
        request_id = request.headers.get('X-Request-ID', '')
        method = request.method
        path = request.path

        # 记录请求日志
        current_app.logger.info(f'Request started: {request_id} {method} {path}')

        # 执行视图函数
        response = f(*args, **kwargs)

        # 计算请求处理时间
        duration = time.time() - start_time

        # 记录响应日志
        current_app.logger.info(
            f'Request completed: {request_id} {method} {path} '
            f'Status: {response.status_code} Duration: {duration:.3f}s'
        )

        return response

    return decorated


def api_key_required(f):
    """API密钥验证中间件"""

    @wraps(f)
    def decorated(*args, **kwargs):
        api_key = request.headers.get('X-API-Key')
        if not api_key:
            return error_response('Missing API key', code=401)

        # 这里可以添加API密钥验证逻辑
        # 例如：检查API密钥是否有效，是否过期等

        return f(*args, **kwargs)

    return decorated


def rate_limit(limit=100, per=60):
    """速率限制中间件"""

    def decorator(f):
        @wraps(f)
        def decorated(*args, **kwargs):
            # 这里可以添加速率限制逻辑
            # 例如：使用Redis记录和检查请求频率

            return f(*args, **kwargs)

        return decorated

    return decorator